package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper mapper;

    public void set(String key, Object value, long timeout, TimeUnit unit) throws JsonProcessingException {
        stringRedisTemplate.opsForValue().set(key, mapper.writeValueAsString(value), timeout, unit);
    }

    public void setWithLogicalExpire(String key, Object value, long timeout, TimeUnit unit) throws JsonProcessingException {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(timeout)));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(key, mapper.writeValueAsString(redisData));
    }

    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, long timeout, TimeUnit unit) throws JsonProcessingException {
        // 1. 从Redis查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2. 判断Redis中是否存在
        if (StrUtil.isNotBlank(json)) {
            // 3. 存在, 直接返回
            return mapper.readValue(json, type);
        }
        // 判断命中的是否是空值
        if (json != null) {
            return null;
        }
        // 4. 不存在, 根据id查询数据库
        R r = dbFallback.apply(id);

        // 5. 数据库中对应数据不存在, 返回错误
        if (r == null) {
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回错误信息
            return null;
        }

        // 6. 存在, 将数据写入Redis
        this.set(key, r, timeout, unit);

        // 7. 返回
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, long timeout, TimeUnit unit) throws JsonProcessingException {
        // 1. 从Redis查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (StrUtil.isBlank(json)) {
            // 3. 不存在, 返回null
            return null;
        }
        // 4. 命中, 需要把json反序列化为对象
        RedisData redisData = mapper.readValue(json, RedisData.class);
        Object data = redisData.getData();
        R r = mapper.convertValue(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5. 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 5.1. 未过期, 直接返回店铺信息
            return r;
        }
        // 5.2. 已过期, 需要缓存重建
        // 6. 缓存重建
        // 6.1. 获取互斥锁
        String lockKey = "lock:" + keyPrefix + id;
        boolean isLock = tryLock(lockKey);
        // 6.2. 判断是否获取锁成功
        if (isLock) {
            // 6.3. 成功, 开启独立线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                // 重建缓存
                try {
                    // 查询数据库
                    R r1 = dbFallback.apply(id);
                    // 写入redis
                    this.setWithLogicalExpire(key, r1, timeout, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        // 6.4. 失败, 返回过期的数据
        return r;
    }

    public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, long timeout, TimeUnit unit) throws JsonProcessingException {
        // 1. 从Redis查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (StrUtil.isNotBlank(json)) {
            // 3. 存在, 直接返回
            return mapper.readValue(json, type);
        }
        // 判断命中的是否是空值, 不是null只能是空字符串
        if (json != null) {
            return null;
        }
        // 4. 实现缓存重建
        // 4.1. 获取互斥锁
        R r = null;
        String lockKey = "lock:" + keyPrefix + id;
        try {
            boolean isLock = tryLock(lockKey);
            // 4.2. 判断是否获取成功
            if (!isLock) {
                // 4.3 失败, 休眠并重试
                Thread.sleep(50);
                return queryWithMutex(keyPrefix, id, type, dbFallback, timeout, unit);
            }
            // 4.4 成功, 根据id查询数据库
            r = dbFallback.apply(id);

            // 5. 商铺不存在, 返回错误
            if (r == null) {
                // 将空值写入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            // 6. 存在, 将数据写入Redis
            this.set(key, r, timeout, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7. 释放互斥锁
            unlock(lockKey);
        }

        // 8. 返回
        return r;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
